package com.general.app.wjgl.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.general.app.wjgl.dao.ISurveySendDao;
import com.general.app.wjgl.dao.entity.SurveySendModel;
import com.general.app.wjgl.service.ISurveySendService;
import com.general.common.service.impl.BaseServiceImpl;
import com.general.utils.base.Constant;
import com.general.utils.base.StringUtil;

public class SurveySendServiceImpl extends BaseServiceImpl<SurveySendModel, ISurveySendDao>
implements ISurveySendService{

	
	/**
	 * 个人发送列表
	 * @param model
	 * @return
	 */
	public List<SurveySendModel> getPagedUserList(SurveySendModel model){
		return dao.getPagedUserList(model);
	}
	

	/**
	 * 问卷绑定
	 * @param model
	 * @return
	 */
	public boolean insert(SurveySendModel model){
		//返回值初始化
		boolean returnFlg = false;
		
		// 按单位/个人
		String tab = model.getTab();

		// 追加被评估者的用户关系
		List<HashMap<String, String>> surveySendLst = new ArrayList<HashMap<String, String>>();

		List<SurveySendModel> assessUserList = new ArrayList<SurveySendModel>();
		HashMap<String, String> surveySendMap = new HashMap<String,String>();
		Date now = new Date();
		SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		
		// 发送ID
		surveySendMap.put("send_id", model.getSend_id());
		// 问卷ID
		surveySendMap.put("survey_id", model.getSurvey_id());
		// 问卷状态 0:未发放
		surveySendMap.put("survey_flg", Constant.SURVEY_FLG_NO);
		// 登陆时间
		surveySendMap.put("insert_dt", f.format(now));
		// 登陆人
		surveySendMap.put("insert_nm", model.getInsert_nm());
		// 更新人
		surveySendMap.put("update_nm", model.getUpdate_nm());	
		// 更新时间
		surveySendMap.put("update_dt", f.format(now));
		
		// 按单位绑定
		if(Constant.TAB_COMPANY.equals(tab)){
			
			// 单位发送FLG（0:单位发送
			surveySendMap.put("company_send_flg", Constant.COMPANY_SEND);

			// 单位ID
			String companyId = model.getCompany_id();
			
			assessUserList = dao.getAssessUserListByCompanyId(companyId);
			
			//按个人绑定
		}else if(Constant.TAB_SINGEL.equals(tab)){

			// 用户
			List<HashMap<String, String>> userLst = new ArrayList<HashMap<String, String>>();
			
			// 单位发送FLG（1：个人发送
			surveySendMap.put("company_send_flg", Constant.SINGLE_SEND);

			// 被评估人
			String assessUsers = model.getAssess_user_id();			
			String[] assessUser = assessUsers.split(",");
			
			for(String s:assessUser){								
				HashMap<String, String> user = new HashMap<String,String>();
				user.put("user_id", s);
				userLst.add(user);
			}	
			assessUserList = dao.getAssessUserListByUserId(userLst);

		}
		
		// 用户关系列表
		if(assessUserList!=null && assessUserList.size()>0){
			for(SurveySendModel s : assessUserList){
				// 设定问卷发放的用户及关系
				HashMap<String, String> surveySend = new HashMap<String,String>(surveySendMap);
				surveySend.put("user_id", s.getUser_id());
				surveySend.put("assess_user_id", s.getAssess_user_id());
				surveySend.put("relation", s.getRelation());
				surveySend.put("company_id", s.getCompany_id());
				
				// 追加到列表
				surveySendLst.add(surveySend);
			}
			int count = dao.batchInsert(surveySendLst);
			if(count!=0){
				returnFlg = true;
			}
		}
		
		return returnFlg;
	}
	
	/**
	 * 删除绑定
	 * @param tab 单位/个人
	 * @param ids 选中记录
	 * @return
	 */
	public String delSurveySend(String tab, String ids) throws Exception {
		List<SurveySendModel> list = getSurveySendList(tab,ids);
		if(list == null) throw new Exception("删除列值为空！");
		int count = dao.batchDelete(list);
		
		// 发送邮件列表
		return count>0 ? "删除成功！" : "成功删除记录"+ids.split(",").length+"条,";

	}

	/**
	 * 返回选中发送信息
	 * @param tab 单位/个人
	 * @param ids 选中记录
	 * @return 选中发送信息
	 */
	private List<SurveySendModel> getSurveySendList(String tab, String ids){

		List<SurveySendModel> list = new ArrayList<SurveySendModel>();
		
		// 解析选择删除记录
		if (!StringUtil.isEmpty(tab) && !StringUtil.isEmpty(ids)) {
			String[] pks = ids.split(",");	
			for (int i = 0; i < pks.length; i++) {
				String[] pk = pks[i].split("_");
				SurveySendModel model = new SurveySendModel();
				//批量删除单位
				if(Constant.TAB_COMPANY.equalsIgnoreCase(tab)){
					// 发送ID
					model.setSend_id(pk[0]);
					// 问卷ID
					model.setSurvey_id(pk[1]);
					// 单位ID
					model.setCompany_id(pk[2]);
					
					//批量删除个人绑定
				}else if(Constant.TAB_SINGEL.equalsIgnoreCase(tab)){
					// 发送ID
					model.setSend_id(pk[0]);
					// 问卷ID
					model.setSurvey_id(pk[1]);
					// 被评估者ID
					model.setAssess_user_id(pk[2]);
				}
				list.add(model);
			}
		}
		return list;
	}
	
	/**
	 * 批量发送邮件
	 * @param tab 单位/个人
	 * @param ids 选中记录
	 */
	public List<String[]> getSendEmailList(String tab, String ids){

		List<SurveySendModel> list = getSurveySendList(tab,ids);
		if(list ==null || list.size()==0){
			return null;
		}
		// 发送邮件列表
		List<SurveySendModel> sendListGet = dao.getSendList(list);
		// 发送邮件列表
		List<String[]> sendList = new ArrayList<String[]>();
		
		// 发送邮件标题
		String subject = "360问卷调查";
		
		for(SurveySendModel s : sendListGet){			
			StringBuffer content = new StringBuffer();
			content.append("您好，" + s.getUser_nm() + "：");
			content.append("<br>");		
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;欢迎您使用【福道-诚壹】-360问卷系统，请点击以下链接回答问卷：");
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;<a style='color:red' href='http://360.fortao.com.cn/login.html?type=answer&username="+ s.getUser_id() + "'>点此开始答卷</a>");
			content.append("<br>");
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;如果上述文字点击无效，请把下面网页地址复制到浏览器地址栏中打开：");		
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;http://360.fortao.com.cn/login.html?type=answer&username="+ s.getUser_id());			
			content.append("<br>");
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;回答完问卷后请注销，谢谢！");
			content.append("<br>");		
			content.append("<br>");		
			content.append("<br>");		
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;From   【福道-诚壹】-360问卷系统");
			
//			// 邮件内容
//			String content = "您好，"
//					+ s.getUser_nm()
//					+ "：<br>&nbsp;&nbsp;&nbsp;&nbsp;欢迎您使用【福道-诚壹】-360问卷系统，请点击以下链接回答问卷：<br>&nbsp;&nbsp;&nbsp;&nbsp;"
//					+ "<a style='color:red' href='http://360.fortao.com.cn/login.html?type=answer&username="
//					+ s.getUser_id() + "'>点此答卷</a><br><br><br><br>From   【福道-诚壹】-360问卷系统";
			
			// 邮件接收对象
			String mailTo = s.getUser_email();

			sendList.add(new String[] { subject, content.toString(), mailTo });			
		}
		return sendList;
	}
	
	/**
	 * 批量【提醒】发送邮件
	 * @param tab 单位/个人
	 * @param ids 选中记录
	 */
	public List<String[]> getSendMindEmailList(String tab, String ids){

		List<SurveySendModel> list = getSurveySendList(tab,ids);
		if(list ==null || list.size()==0){
			return null;
		}
		// 发送邮件列表
		List<SurveySendModel> sendListGet = dao.getSendList(list);
		
		// 发送邮件列表
		List<String[]> sendList = new ArrayList<String[]>();
		
		// 发送邮件标题
		String subject = "360问卷调查-问卷回答提醒";
		
		for(SurveySendModel s : sendListGet){			

			StringBuffer content = new StringBuffer();

			content.append("您好，" + s.getUser_nm() + "：");
			content.append("<br>");		
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;欢迎您使用【福道-诚壹】-360问卷系统，请尽快提交问卷!");
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;请点击以下链接回答问卷：");			
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;<a style='color:red' href='http://360.fortao.com.cn/login.html?type=answer&username="+ s.getUser_id() + "'>点此开始答卷</a>");
			content.append("<br>");
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;如果上述文字点击无效，请把下面网页地址复制到浏览器地址栏中打开：");			
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;http://360.fortao.com.cn/login.html?type=answer&username="+ s.getUser_id());			
			content.append("<br>");
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;回答完问卷后请注销，谢谢！");
			content.append("<br>");
			content.append("<br>");
			content.append("<br>");
			content.append("<br>");
			content.append("&nbsp;&nbsp;&nbsp;&nbsp;From   【福道-诚壹】-360问卷系统");
			
//			// 邮件内容
//			String content = "您好，"
//					+ s.getUser_nm()
//					+ "：<br>&nbsp;&nbsp;&nbsp;&nbsp;欢迎您使用【福道-诚壹】-360问卷系统，请尽快提交问卷!<br>点击以下链接回答问卷：<br>&nbsp;&nbsp;&nbsp;&nbsp;"
//					+ "<a style='color:red' href='http://360.fortao.com.cn/login.html?type=answer&username="
//					+ s.getUser_id() + "'>点此答卷</a><br><br>From   【福道-诚壹】-360问卷系统";
			
			// 邮件接收对象
			String mailTo = s.getUser_email();

			sendList.add(new String[] { subject, content.toString(), mailTo });			
		}
		return sendList;
	}

	/**
	 * 返回选中发送信息[提交状态更新用]
	 * @param tab 单位/个人
	 * @param ids 选中记录
	 * @return 选中发送信息
	 */
	private List<SurveySendModel> getSurveyUpdateSubmitList(String tab, String ids){

		List<SurveySendModel> list = new ArrayList<SurveySendModel>();
		
		// 解析选择删除记录
		if (!StringUtil.isEmpty(tab) && !StringUtil.isEmpty(ids)) {
			String[] pks = ids.split(",");	
			for (int i = 0; i < pks.length; i++) {
				String[] pk = pks[i].split("_");
				SurveySendModel model = new SurveySendModel();
				//批量删除单位
				if(Constant.TAB_COMPANY.equalsIgnoreCase(tab)){
					// 发送ID
					model.setSend_id(pk[0]);
					// 问卷ID
					model.setSurvey_id(pk[1]);
					// 单位ID
					model.setCompany_id(pk[2]);

					// 提交状态old:1：已保存
					model.setSumbit_flg_old(Constant.SUBMIT_FLG_SAVE);
					
					//批量删除个人绑定
				}else if(Constant.TAB_SINGEL.equalsIgnoreCase(tab)){
					
					// 发送ID
					model.setSend_id(pk[0]);
					
					// 问卷ID
					model.setSurvey_id(pk[1]);
					
					// 被评估者ID
					model.setAssess_user_id(pk[2]);

					// 提交状态old:1：已保存
					model.setSumbit_flg_old(Constant.SUBMIT_FLG_SAVE);
				}
				list.add(model);
			}
		}
		return list;
	}
	/**
	 * 问卷发放
	 * @param tab 单位/个人
	 * @param ids 选中记录
	 * @user 用户
	 * @return
	 */
	public int sendSurveySend(String tab, String ids) throws Exception {
		
		List<SurveySendModel> list = getSurveySendList(tab,ids);
		if(list == null) throw new Exception("发送列值为空！");
		int count = dao.batchSend(list);
		return count ;
		
	}

	/**
	 * 问卷发放结束
	 * @param tab 单位/个人
	 * @param ids 选中记录
	 * @user 用户
	 * @return
	 */
	public String endSurveySend(String tab, String ids) throws Exception {
		
		List<SurveySendModel> list = getSurveySendList(tab,ids);
		if(list == null) throw new Exception("发放结束列值为空！");
		int count = dao.batchEnd(list);
		
		if(count > 0 ){
			
			// 提交状态列表
			list = getSurveyUpdateSubmitList(tab,ids);
			
			HashMap<String, Object> map=new HashMap<String, Object>();
			map.put("submit_flg", Constant.SUBMIT_FLG_YES);
			map.put("list", list);
			
			// 更新提交状态
			dao.batchUpdSubmitFlg(map);
		}
		
		return count>0 ? "发放结束成功！" : "成功发放结束记录"+ids.split(",").length+"条,";
		
	}

	/**
	 * 批量更新问卷发放结束（更新提交状态：2:已保存=>1:已提交）
	 * @param surveySendLst
	 * @return
	 */
	public int batchUpdSubmitFlg(Map<String,Object> map){
		
		return dao.batchUpdSubmitFlg(map);
	}
	
	/**
	 * 根据ID取得关系列表
	 * @param list
	 * @return
	 */
	public List<SurveySendModel> getAssessSendList(String ids){

		if(ids==null || "".equalsIgnoreCase(ids)) return null;
		List<SurveySendModel> lst = new ArrayList<SurveySendModel>();
		String[] pks = ids.split("_");
		SurveySendModel model = new SurveySendModel();
		// 发送ID
		model.setSend_id(pks[0]);
		// 问卷ID
		model.setSurvey_id(pks[1]);
		
		// 被评估者ID
		model.setAssess_user_id(pks[2]);
		lst.add(model);
		return dao.getAssessSendList(lst);
	}
	
}
